//
//  MacroMethod.swift
//  宏-方法
//
//  Created by mini on 2025/4/28.
//

import Foundation

func W(_ n: CGFloat) -> CGFloat {
    return n * SCREEN_WIDTH / 375.0
}

func isStr<T>(_ value: T?) -> Bool {
    if let stringValue = value as? String, !stringValue.isEmpty {
        return true
    } else {
        return false
    }
}

func isAry<T>(_ array: T?) -> Bool {
    if let array = array as? any Collection, array.count > 0 {
        return true
    }
    return false
}

struct XY {
    var x: CGFloat
    var y: CGFloat
    init(_ x: CGFloat, _ y: CGFloat) {
        self.x = x
        self.y = y
    }
}

// 解包
func UnPackStr<T>(_ value: T?) -> String {
    switch value {
    case let str as String:
        if str.isEmpty { return "" }
        return str
    case let int as Int:
        return "\(int)"
    case let double as Double:
        // 检查是否为整数
        if double.truncatingRemainder(dividingBy: 1) == 0 {
            return "\(Int(double))"
        }
        return String(format: "%.2f", double)
    case let float as Float:
        // 检查是否为整数
        if float.truncatingRemainder(dividingBy: 1) == 0 {
            return "\(Int(float))"
        }
        return String(format: "%.2f", float)
    case let number as NSNumber:
        return "\(number)"
    case let bool as Bool:
        return bool ? "1" : "0"
    case .none:
        return ""
    default:
        return ""
    }
}

// 解包 - 设置默认值
func UnPackDefaultStr<T>(_ value: T?, _ defaultStr: String) -> String {
    if let value = value as? String {
        return isStr(value) ? value : defaultStr
    } else if let value = value as? NSNumber {
        return isStr("\(value)") ? "\(value)" : defaultStr
    } else {
        return defaultStr
    }
}
